package cn.lcfms.app.weixin.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.lcfms.app.admin.bean.DemoBean;
import cn.lcfms.app.weixin.service.WxApiService;
import cn.lcfms.app.weixin.util.WeixinDecrypMsg;
import cn.lcfms.app.weixin.util.WeixinEvent;
import cn.lcfms.app.weixin.util.WeixinMsg;
import cn.lcfms.bin.annotation.PermitPoll;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.bin.view.CommonEditView;
import cn.lcfms.bin.view.CommonPageView;
import cn.lcfms.utils.HttpUtils;
import cn.lcfms.utils.TimeUtils;
import net.sf.json.JSONObject;

@PermitPoll(type="微信API",name="参数配置")
@Controller("weixin.ConfigController")
@RequestMapping("/weixin/config")
public class ConfigController extends WeixinBaseController{
	private static Logger logger = Logger.getLogger(ConfigController.class); 
	@Autowired
	private WxApiService ws;	
	@RequestMapping("/init")
	public CommonEditView init(HttpServletRequest request) {
		CommonEditView view=new CommonEditView("微信配置");
		view.setInputForm("服务器地址(URL)", "url", request.getAttribute("APP")+"weixin/config/notice", "readonly");
		view.setInputForm("AppId", "appid", ws.getAppid(), "");
		view.setInputForm("AppSecret", "AppSecret", ws.getAppSecret(), "");
		view.addObject("token", ws.getToken());
		view.setViewForm("weixin/token.jsp");
		view.setInputForm("EncodingAESKey", "EncodingAESKey", ws.getEncodingAESKey(), "");
		view.setInputForm("最新access_token", "access_token", ws.getAccess_token(), "");	
		view.setFormAction("save");
		view.setMethodAjax();
		return view;
	}	
	
	@RequestMapping("/save")
	public String save(HttpServletRequest request) {
		BaseService service = Application.getService("weixin");
		@SuppressWarnings("rawtypes")
		Enumeration names = request.getParameterNames();
		while(names.hasMoreElements()) {
			String name = (String) names.nextElement();
			service.where("name", name).setData(request.getParameter(name)).update("value");
		}
		ws.freshConfig();
		return "{code:1,msg:保存成功！,url:init}";
	}
	
	/*
	 * 微信消息处理
	 */
	@RequestMapping("/notice")
	@PermitPoll(type="all")
	@ResponseBody
	public String notice(HttpServletRequest request,HttpServletResponse response) throws IOException{	
		Enumeration<String> p = request.getParameterNames();
		while(p.hasMoreElements()) {
			String e =p.nextElement();
			logger.info(e+"=>"+request.getParameter(e));
		}
		ServletInputStream ris = request.getInputStream();
		if(null!=ris) {
			StringBuffer content = new StringBuffer();  
			byte[] b = new byte[1024];  
			int lens = -1;  
			while((lens = ris.read(b))>0) {  
			     content.append(new String(b, 0, lens));  
			}  
			//处理微信消息
			if(content.length()>0) {
				String str = content.toString();
				String msg_signature=request.getParameter("msg_signature");
				String timestamp=request.getParameter("timestamp");
				String nonce=request.getParameter("nonce");
				String openid=request.getParameter("openid");
				JSONObject msg = WeixinDecrypMsg.decryptMsg(ws,msg_signature, timestamp, nonce, str);				
				String MsgType = msg.getString("MsgType");				
				String myOpenId = msg.getString("ToUserName");
				WeixinMsg weixinMsg=new WeixinMsg();
				weixinMsg.setFromUserName(myOpenId);
				weixinMsg.setToUserName(openid);
				weixinMsg.setCreateTime(TimeUtils.getCurrentShortTime());
				switch (MsgType) {
				//事件消息处理
				case "event":
					String Event = msg.getString("Event");
					String EventKey = "";
					if(msg.containsKey("EventKey")) {
						EventKey=msg.getString("EventKey");
					}
					//点击菜单事件
					if(Event.equals("CLICK")) {						
						BaseService service= Application.getService("wxmenu");
						String message = service.where("id="+EventKey).selectColumn("message");
						weixinMsg.setContent(message);
						String textMsg = weixinMsg.textMsg();
						return textMsg;
					}	
					//扫一扫事件，完毕后将结果发送给用户，url则跳转
					if(Event.equals("scancode_push")) {
						JSONObject ScanCodeInfo=msg.getJSONObject("ScanCodeInfo");
						return WeixinEvent.scancode_push(weixinMsg,EventKey,ScanCodeInfo);
					}
					//扫一扫事件，完毕后关闭照相机
					if(Event.equals("scancode_waitmsg")) {
						JSONObject ScanCodeInfo=msg.getJSONObject("ScanCodeInfo");
						return WeixinEvent.scancode_waitmsg(weixinMsg,EventKey,ScanCodeInfo);
					}
					//调用照相机事件
					if(Event.equals("pic_sysphoto")) {
						JSONObject SendPicsInfo=msg.getJSONObject("SendPicsInfo");
						return WeixinEvent.pic_sysphoto(weixinMsg,EventKey,SendPicsInfo);
					}
					//调用照相机或获取系统相册相片事件
					if(Event.equals("pic_photo_or_album")) {
						JSONObject SendPicsInfo=msg.getJSONObject("SendPicsInfo");
						return WeixinEvent.pic_photo_or_album(weixinMsg,EventKey,SendPicsInfo);
					}
					//调用微信相册事件
					if(Event.equals("pic_weixin")) {
						JSONObject SendPicsInfo=msg.getJSONObject("SendPicsInfo");
						return WeixinEvent.pic_weixin(weixinMsg,EventKey,SendPicsInfo);
					}
					//获取位置事件
					if(Event.equals("location_select")) {	
						JSONObject SendLocationInfo=msg.getJSONObject("SendLocationInfo");
						return WeixinEvent.location_select(weixinMsg,EventKey,SendLocationInfo);
					}				
				//图片消息处理	
				case "image":
					weixinMsg.setContent("图片已经收到，谢谢支持！");					
					return weixinMsg.textMsg();
				//位置消息处理
				case "location":
					weixinMsg.setContent("位置已经收到，谢谢支持！");					
					return weixinMsg.textMsg();
					//文本消息
				case "text":
					weixinMsg.setContent("你想干嘛?");
					return weixinMsg.textMsg();
				default:
					break;
				}
			}
		}		
		String echostr=request.getParameter("echostr");
		//验证微信公众号
		if(null!=echostr) {
			return echostr;
		}		
		return "success";
	}
	
	//获取用户信息begin
	@ResponseBody
	@RequestMapping(value="/login",produces="text/html;charset=utf-8")
	@PermitPoll(type="all")
	public String login() throws Exception {
		String appid=ws.getAppid();
		String redirect_uri="http://weixin.8s00.com/weixin/config/userinfo";
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+URLEncoder.encode(redirect_uri, "utf-8")+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";    
		return "<script>location.href=\""+url+"\"</script>";
	}
	
	//获取用户信息end
	@RequestMapping("/postview")
	@PermitPoll(type="all")
	public String postview(HttpServletRequest request) throws Exception {		
		return "admin/frame/test";
	}
	
	//获取用户信息end
	@RequestMapping("/userinfo")
	@PermitPoll(type="all")
	public String userinfo(HttpServletRequest request) throws Exception {
		Enumeration<String> p = request.getParameterNames();
		while(p.hasMoreElements()) {
			String e =p.nextElement();
			logger.info(e+"=>"+request.getParameter(e));
		}
		String code=request.getParameter("code");
		String appid=ws.getAppid();
		String secret=ws.getAppSecret();
		String url="  https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		byte[] dataByte = HttpUtils.getDataByte(url);
		String str=new String(dataByte);
		JSONObject object=JSONObject.fromObject(str);
		String openid = (String) object.get("openid");
		String access_token = (String) object.get("access_token");
		url=" https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		dataByte = HttpUtils.getDataByte(url);
		str=new String(dataByte,"utf-8");
		System.out.println(str);
		BaseService service = Application.getService(DemoBean.class);
		List<HashMap<String, Object>> list = service.selectList();
		request.setAttribute("list", list);
		return "admin/frame/test";
	}

	@RequestMapping("/post")
	public String post(DemoBean bean) {
		BaseService service= Application.getService(DemoBean.class);
		service.insert(bean);
		return "{code:1,msg:添加成功！,url:userinfo}";
	}
	
	@RequestMapping("/txl")
	public CommonPageView txl() {
		BaseService service= Application.getService(DemoBean.class);
		service.column("name as 姓名","mobile as 手机","address as 地址","work as 工作","hobby as 爱好","remark as 备注");
		CommonPageView view=new CommonPageView("通讯录管理",service);
		view.setFilterInputLike("姓名", "name", "");
		view.setFilterInputLike("手机", "mobile", "");
		return view;
	}
}
